<template>
  <div class="coinrevenue-detail report-container table_zoom">
    <Row type="flex"
         justify="space-between"
         class="coinrevenue-list-edit">
      <Row type="flex"
           align="middle">
        <Col>
        <span class="concrete-data">时间：</span>
        <datePickerYmd @on-change="search"
                       :selectDateType.sync='selectDateType'
                       :dataType="dataType"
                       v-model="timeDate"
                       :dateOption="dateOption"
                       style="display:inline-block"></datePickerYmd>
        </Col>
        <Row type="flex"
             align="middle"
             class="export-btn">
          <Col>
          <!-- <Select v-model="searchObj.shopId"
                  multiple
                  filterable
                  class="select-shop-item"
                  :max-tag-count="1"
                  @on-change="selectshop"
                  :max-tag-placeholder="maxTagPlaceholder"
                  style="width:210px">
            <Option v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select> -->
          <!-- <vueTreeselectShop :shopList.sync="searchObj.shopId"
                             @id-change="search"
                             permissionCode="moms:report:coinrevenue"
                             v-model="testValue"></vueTreeselectShop> -->
          <vueTreeselectChoice :multiple="true"
                               ref="vueTreeselectChoice"
                               @input="handleShop"
                               @on-api-finish="apiFinish"
                               permissionCode="moms:report:coinrevenue"
                               v-model="ShopValue"></vueTreeselectChoice>
          </Col>
          <Col>
          <Button type="primary"
                  class="coinrevenue-btn export-btn"
                  @click="search">查询</Button>
          </Col>
        </Row>
      </Row>
      <Col>
      <Button class="coinrevenue-btn export-btn"
              @click="exportData"
              v-if="hasPermission('moms:report:coinrevenueexport')">导出</Button>
      </Col>
    </Row>
    <Table stripe
           ref="rowSpanTable"
           :loading="isloading"
           :height="this.tableHeight"
           class="table-list"
           border
           v-show="isTrue"
           :columns="columns"
           :data="resData">
      <template slot-scope="{ row }"
                slot="depositNum">
        <saasPoptip trigger="hover"
                    content="上期期末存币数+当期售赠币总数-当期机台吸币数">
          <span class="deposit">{{row.depositNum}}</span>
        </saasPoptip>
      </template>
      <template slot-scope="{ row }"
                slot="unitCoinAmount">
        <saasPoptip trigger="hover"
                    content="（上期期末存币金额+当期游戏币营收）/（上期期末存币总数+当期游戏币售赠数）">
          <span class="deposit">{{row.unitCoinAmount}}</span>
        </saasPoptip>
      </template>
      <template slot-scope="{ row }"
                slot="depositAmount">
        <saasPoptip trigger="hover"
                    content="期末存币总数*单位币值">
          <span class="deposit">{{row.depositAmount}}</span>
        </saasPoptip>
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px"
         v-show="isTrue">
      <Page :total="total"
            ref="pages"
            :current.sync="searchObj.offset"
            :page-size="searchObj.limit"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            :page-size-opts="$pageSizeOpts"
            show-total />
    </div>
    <down-center ref="downCenterRef"
                 perms="moms:report:coinrevenue"
                 v-if="hasPermission('moms:report:coinrevenueexport')"></down-center>
  </div>
</template>

<script>
import '../../report.less'
import { coinDetailDaily } from '@/api/report/finance'
import { formatAmount } from '@/libs/tools'
import datePickerYmd from '@/components/date-picker-ymd/date-picker-ymd.vue'
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
// import { blobToXls } from '@/libs/blobToXls'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
import dayjs from 'dayjs'
import saasPoptip from '@/components/saas-poptip'
import DownCenter from '@/view/components/down-center/index.vue'
export default {
  name: 'report_finance_coinrevenue_detail',
  components: { vueTreeselectChoice, datePickerYmd, saasPoptip, DownCenter },
  data () {
    return {
      dataChoose: '',
      options: [],
      value: null,
      shopName: null,
      ShopValue: [],
      shopList: [],
      tableHeight: 0,
      dataType: [{ key: 'date', value: '日' }, { key: 'month', value: '月' }, { key: 'year', value: '年' }],
      timeDate: JSON.parse(localStorage.getItem('obj')) ? JSON.parse(localStorage.getItem('obj')).timeDate : JSON.parse(localStorage.getItem('upObj')).timeDate,
      selectDateType: JSON.parse(localStorage.getItem('obj')) ? JSON.parse(localStorage.getItem('obj')).selectDateType : JSON.parse(localStorage.getItem('upObj')).selectDateType,
      isloading: false,
      tableData: [], // 保存原始数据
      total: 0,
      detailDailyVOs: [],
      testValue: JSON.parse(localStorage.getItem('obj')) ? JSON.parse(localStorage.getItem('obj')).id : JSON.parse(localStorage.getItem('upObj')).id,
      searchObj: {
        shopId: [],
        offset: 1,
        limit: 10
      },
      dateOption: {
        disabledDate: date => {
          if (process.env.NODE_BUILD === 'prod') return dayjs(date).isAfter(dayjs(new Date()).subtract(1, 'day'))
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      resData: [],
      isTrue: false,
      columns: [
        { title: '门店', key: 'shopName', align: 'center', fixed: 'left', width: 200 },
        { title: '日期', key: 'statDate', align: 'center', width: 120 },
        { title: '游戏币营收(元)', key: 'coinSaleAmount', align: 'center', width: 120 },
        { title: '游戏币售赠(枚)', key: 'coinGiftNum', align: 'center', width: 120 },
        {
          title: '机台吸币统计',
          align: 'center',
          children: [{ title: '机台吸币总数', key: 'machineReceiveNum', align: 'center', width: 110 }]
        },
        { title: '期末存币总数(枚)', key: 'depositNum', align: 'center', width: 130, slot: 'depositNum' },
        { title: '单位币值(元)', key: 'unitCoinAmount', align: 'center', width: 130, slot: 'unitCoinAmount' },
        { title: '期末存币金额(元)', key: 'depositAmount', align: 'center', width: 130, slot: 'depositAmount' },
        {
          title: '币值收入(元)',
          // key: 'coinAdd',
          align: 'center',
          children: [
            { title: '合计', key: 'totalAmount', align: 'center', width: 90 },
            { title: '游戏收入', key: 'gameAmount', align: 'center', width: 90 },
            { title: '商品销售', key: 'productSaleAmount', align: 'center', width: 90 },
            { title: '出租收入', key: 'rent', align: 'center', width: 90 }
          ]
        }
      ]
    }
  },
  computed: {
    startDate () {
      return this.timeDate[0]
    },
    endDate () {
      return this.timeDate[1]
    }
  },
  mounted () {
  },
  updated () {
    this.$nextTick(() => {
      // rowSpanTable(this.$refs.rowSpanTable, 'shopName', 'left')
    })
  },
  destroyed () {
    localStorage.removeItem('obj')
  },
  methods: {
    // 门店改变
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.searchObj.shopId = ids
      localStorage.setItem('upObj', JSON.stringify({ id: this.searchObj.shopId, type: this.selectDateType, timeDate: this.timeDate, selectDateType: this.selectDateType }))
      this.search()
    },
    apiFinish () {
      this.ShopValue = JSON.parse(localStorage.getItem('obj')) ? JSON.parse(localStorage.getItem('obj')).id : JSON.parse(localStorage.getItem('upObj')).id
    },
    getList () {
      this.isloading = true
      this.resData = []
      this.tableHeight = 0
      coinDetailDaily({
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopId,
        startDate: this.startDate,
        endDate: this.endDate,
        offset: (this.searchObj.offset - 1) * this.searchObj.limit,
        limit: this.searchObj.limit
      }).then(res => {
        this.isloading = false
        if (res.data.status === 200) {
          this.isTrue = true
          this.total = res.data.totalCount
          if (res.data.data.hasOwnProperty('detailDailyVOs')) {
            if (res.data.data.detailDailyVOs.length && res.data.data.detailDailyVOs.length >= 14) {
              this.tableHeight = 700
            }
          } else {
            this.tableHeight = 0
          }
          // 设置单元格
          this.tableData = res.data.data.machineCategories ? res.data.data.machineCategories : []

          let arr = this.tableData.map(ele => {
            let obj = {
              title: ele.name,
              key: ele.machineCategoryId,
              align: 'center',
              children: [
                { title: '币数', key: `${ele.machineCategoryId}coinNum`, align: 'center', width: 150 },
                { title: '金额', key: `${ele.machineCategoryId}coinAmout`, align: 'center', width: 150 }
              ]
            }
            return obj
          })

          this.columns.map(eld => {
            if (eld.title === '机台吸币统计') {
              eld.children.push(...arr)
              let result = {}
              let finalResult = []
              eld.children.forEach((item, idx, art) => {
                result[art[idx].title] = art[idx]
              })
              Object.keys(result).forEach(key => {
                finalResult.push(result[key])
              })
              eld.children = finalResult
            }
          })
          //  let key1 = `${elt.machineCategoryId}coinNum`
          //   let key2 = `${elt.machineCategoryId}coinAmout`
          //   obj.key1 = elt.coinNum
          //   obj.key2 = elt.coinAmout
          if (res.data.data.detailDailyVOs) {
            this.detailDailyVOs = res.data.data.detailDailyVOs
            this.detailDailyVOs.map(ele => {
              ele.coinCategoryVOs.map(elt => {
                // this.$set(ele, 'coinNum', elt.coinNum)
                // this.$set(ele, 'coinAmout', elt.coinAmout)
                this.$set(ele, `${elt.machineCategoryId}coinNum`, elt.coinNum)
                this.$set(ele, `${elt.machineCategoryId}coinAmout`, formatAmount(elt.coinAmout))
              })
            })
            this.resData = this.filterResData(this.detailDailyVOs)
          } else {
            this.resData = []
          }
          // console.log('dd', this.resData)
          // this.$nextTick(() => {
          //   rowSpanTable(this.$refs.rowSpanTable, 'shopName', 'left')
          // })
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 千分位金钱
    filterResData (data) {
      data.map(ele => {
        Object.keys(ele).forEach(key => {
          // if(key!=='coinGiftNum'&&key!=='depositNum'&&key!=='coinCategoryVOs'&&key!=='machineReceiveNum'&&key!=='shopId'&&key!=='shopName'&&key!=='statDate'&&key.indexOf('Num')===-1)
          if (key.indexOf('Num') === -1 && key !== 'shopId' && key !== 'shopName' && key !== 'statDate') {
            ele[key] = formatAmount(ele[key])
          } if (key === 'rent') {
            ele[key] = formatAmount(ele[key])
          }
        })
      })
      return data
    },
    // 导出
    exportData () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        let obj = { 'date': '0', 'month': '1', 'year': '2' }
        this.$refs.downCenterRef.addTask({
          merchantId: this.$store.state.user.merchantId,
          shopIds: this.searchObj.shopId,
          startDate: this.startDate,
          endDate: this.endDate,
          dateType: obj[this.selectDateType],
          taskModule: 'coinRevenueDetail'
        })
        // coinDetailDailyExport({
        //   merchantId: this.$store.state.user.merchantId,
        //   shopIds: this.searchObj.shopId,
        //   startDate: this.startDate,
        //   endDate: this.endDate
        // }).then(res => {
        //   if (res.status === 200) {
        //     if (this.selectDateType === 'date') {
        //       blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 10)})`)
        //     } else if (this.selectDateType === 'month') {
        //       blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 7)})`)
        //     } else {
        //       blobToXls(res.data, `游戏币收入明细表(${this.startDate.substring(0, 4)})`)
        //     }
        //   }
        // })
      }
    },
    // 查询
    search () {
      if (!dayjs(this.startDate).isValid()) {
        this.$Message.error(`请选择时间`)
      } else if (!this.searchObj.shopId.length) {
        this.$Message.error(`请选择门店列表`)
      } else {
        this.searchObj.offset = 1
        this.searchObj.limit = 10
        this.getList()
      }
    },
    // 获取页码
    handlePage (val) {
      this.searchObj.offset = val
      this.getList()
    },
    handlePageSize (pageSize) {
      this.searchObj.limit = pageSize
      this.getList()
    }
  }
}
</script>
<style>
</style>
